package pw.hais.bankcalling.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hs.usbsdk.UsbController;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import android_serialport_api.CHexConver;
import pw.hais.bankcalling.R;
import pw.hais.bankcalling.app.BaseActivity;
import pw.hais.bankcalling.app.HaisApp;
import pw.hais.bankcalling.app.V;
import pw.hais.bankcalling.dao.BankCallingDao;
import pw.hais.bankcalling.dao.DateCacheDao;
import pw.hais.bankcalling.entity.Machine;
import pw.hais.bankcalling.model.CallingModel;
import pw.hais.bankcalling.model.RegisterModel;
import pw.hais.bankcalling.service.CallService;
import pw.hais.bankcalling.service.EventService;
import pw.hais.bankcalling.utils.print.SerialPortPrinter;
import pw.hais.bankcalling.utils.print.USBPrinter;
import pw.hais.http.base.OnHttpListener;
import pw.hais.utils.AppInfoUtil;
import pw.hais.utils.AppNetInfoUtil;
import pw.hais.utils.DownTime;
import pw.hais.utils.EmptyUtil;
import pw.hais.utils.L;
import pw.hais.utils.SPUtil;

/**
 * 启动初始页
 */
public class StartActivity extends BaseActivity implements View.OnClickListener {
    private EditText edit_channel_no, edit_name, edit_dev_no;
    private Button btn_push;
    private TextView text_msg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        text_msg = (TextView) findViewById(R.id.text_msg);

        //如果机器未注册，则提示注册
        if (EmptyUtil.emptyOfObject(HaisApp.machine)) {
            HaisApp.machine = new Machine();
            findViewById(R.id.layout_register).setVisibility(View.VISIBLE);
            edit_channel_no = (EditText) findViewById(R.id.edit_channel_no);
            edit_name = (EditText) findViewById(R.id.edit_name);
            edit_dev_no = (EditText) findViewById(R.id.edit_dev_no);
            btn_push = (Button) findViewById(R.id.btn_push);
            btn_push.setOnClickListener(this);
        } else {
            //初始化USB打印机
//            USBPrinter.usb_print = new UsbController(this, new Handler() {
//                @Override
//                public void handleMessage(Message msg) {
//                    switch (msg.what) {
//                        case UsbController.USB_CONNECTED:
//                            Toast.makeText(getApplicationContext(), "已获取USB设备访问权限", Toast.LENGTH_SHORT).show();
//                            break;
//                        default:
//                            break;
//                    }
//                }
//            });
//
//            USBPrinter.usb_print_dev = USBPrinter.usb_print.getDev(0x0471, 0x0055);
//            if (USBPrinter.usb_print_dev != null && !USBPrinter.usb_print.isHasPermission(USBPrinter.usb_print_dev)) {
//                USBPrinter.usb_print.getPermission(USBPrinter.usb_print_dev); //获取权限
//            }
//
//            if(USBPrinter.usb_print_dev == null) L.showShort("USB打印机 打开失败！");
            getServerBankCallingTemp();
        }
    }

    //注册机器
    private void registerMachine() {
        HaisApp.machine.native_code = AppInfoUtil.getUnique_code();
        HaisApp.machine.ip = AppNetInfoUtil.getLocalIpAddress();
        HaisApp.machine.mac = AppInfoUtil.getMACAddress();
        loadDialogShow("正在注册设备...");
        BankCallingDao.machineRegister(HaisApp.machine, new OnHttpListener<RegisterModel>() {
            @Override
            public void onSuccess(Response response, RegisterModel data) {
                loadDialogDismiss();
                if (data.code == 0) {
                    HaisApp.machine.appkey = data.data.appkey;
                    SPUtil.saveObject(V.SP_MACHINE_MODEL_KEY, HaisApp.machine);
                    getServerBankCallingTemp();
                } else if (data.code == 100) {
                    HaisApp.machine.appkey = data.APP_KEY;
                    HaisApp.machine.channel_no = data.channel_no;
                    HaisApp.machine.dev_no = data.DEV_NO;
                    HaisApp.machine.dev_name = data.DEV_NAME;
//                    L.showLong("设备不能重复注册，现已使用上次注册信息 " + HaisApp.machine.dev_name + " 重新初始化");
                    SPUtil.saveObject(V.SP_MACHINE_MODEL_KEY, HaisApp.machine);
                    getServerBankCallingTemp();
                } else {
                    L.showShort("请求失败," + data.msg + " (" + data.code + ")");
                }
            }

            @Override
            public void onError(Request request, Exception e) {
                super.onError(request, e);
                loadDialogShow("服务器数据获取出错，请联系管理员后重启机器！");
            }
        });

    }

    //獲取服務器模版
    private void getServerBankCallingTemp() {
        loadDialogShow("正在获取 排队模版 ...");
        BankCallingDao.getServerInitDate(new OnHttpListener<CallingModel>() {
            @Override
            public void onSuccess(Response response, final CallingModel data) {
                try {
                    HaisApp.machine.template = data.data.template.get(0).Text;
                } catch (Exception e) {
                    e.printStackTrace();
                    L.showLong("打印模版获取出错！");
                }
                //预处理数据存到缓存
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DateCacheDao.saveCallingInfo(data.data);
                    }
                }).start();
                startMainActivity();
            }

            @Override
            public void onError(Request request, Exception e) {
                super.onError(request, e);
                loadDialogShow("服务器数据获取出错，请联系管理员后重启机器！");
            }
        });
    }


    private void startMainActivity() {
        findViewById(R.id.layout_register).setVisibility(View.GONE);
        new DownTime(3 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                text_msg.setText("(" + ((int) millisUntilFinished / 1000) + "秒后跳转到主页)");
            }

            @Override
            public void onFinish() {
                loadDialogDismiss();
                startService(new Intent(context, EventService.class));  //接收事件服务
                startService(new Intent(context, CallService.class));   //发送事件服务
                startActivity(new Intent(context, MainActivity.class)); //主界面
                finish();
            }
        }.start();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_push:
                HaisApp.machine.dev_type = "1";
                HaisApp.machine.channel_no = edit_channel_no.getText() == null ? "" : edit_channel_no.getText().toString().trim();
                HaisApp.machine.dev_name = edit_name.getText() == null ? "" : edit_name.getText().toString().trim();
                HaisApp.machine.dev_no = edit_dev_no.getText() == null ? "" : edit_dev_no.getText().toString().trim();
                if (EmptyUtil.emptyOfString(HaisApp.machine.channel_no) || EmptyUtil.emptyOfString(HaisApp.machine.dev_name) || EmptyUtil.emptyOfString(HaisApp.machine.dev_no)) {
                    L.showShort("请输入所有信息，不能留空。");
                } else {
                    registerMachine();
                }
                break;
        }
    }
}
